package com.coscon.service.impl;

import com.coscon.mapper.SysConfigMapper;
import com.coscon.model.db.SysConfig;
import com.coscon.service.FtpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.impl.DefaultConnectionConfig;
import org.apache.ftpserver.listener.Listener;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.ConcurrentLoginPermission;
import org.apache.ftpserver.usermanager.impl.TransferRatePermission;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class FtpServiceImpl implements FtpService {
    @Resource
    private SysConfigMapper sysConfigMapper;

    FtpServer server = null;

    FtpServerFactory serverFactory = null;

    //绑定的地址
    private String bindAdress = "0.0.0.0";
    private String defaultPort = "21";

    @Override
    public boolean initFtpServer() throws FtpException {
        if(this.serverFactory!=null){
            Map<String, Listener> mapl = this.serverFactory.getListeners();
            if(mapl!=null && !mapl.isEmpty()){
                for (Map.Entry<String, Listener> entry : mapl.entrySet()) {
                    Listener l  = entry.getValue();
                    if(l!=null){
                        l.stop();
                    }
                }
            }
            this.serverFactory = null;
        }
        if(this.server!=null && !this.server.isStopped()){
            log.debug("ftp server 正在运行，执行停止");
            this.server.stop();
            this.server  = null;
            this.serverFactory = null;
        }


        log.debug("---------------------initFtpServer--------------------------");
        //从配置中获取参数
        Map<String, String> map = this.getSysconfigValByKeys(
                "security_is_ftp"
                ,"security_ftp_port"
                ,"security_ftp_username"
                ,"security_ftp_password"
                ,"security_ftp_root_dir"
        );
        String securityIsFtp = map.get("security_is_ftp")!=null?map.get("security_is_ftp").toString():"";
        String securityFtpPort = map.get("security_ftp_port")!=null?map.get("security_ftp_port").toString():defaultPort;
        String securityFtpUsername = map.get("security_ftp_username")!=null?map.get("security_ftp_username").toString():"admin";
        String securityFtpPassword = map.get("security_ftp_password")!=null?map.get("security_ftp_password").toString():"123456";
        String securityFtpRootDir = map.get("security_ftp_port")!=null?map.get("security_ftp_root_dir").toString():"d:\\";
        if(!StringUtils.equalsIgnoreCase(securityIsFtp,"on")){
            log.debug("ftp 服务禁用");
            return false;
        }
        if(this.serverFactory==null){
            serverFactory = new FtpServerFactory();
        }

        //ListenerFactory
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(NumberUtils.toInt(securityFtpPort,NumberUtils.toInt(defaultPort)));
        factory.setServerAddress(bindAdress);
        serverFactory.addListener("default", factory.createListener());

        //DefaultConnectionConfig
        boolean anonymousLoginEnabled = true;
        int loginFailureDelay = 10;
        int maxLogins = 10;
        int maxAnonymousLogins = 10;
        int maxLoginFailures  = 10;
        int maxThreads = 10;
        DefaultConnectionConfig defaultConnectionConfig = new DefaultConnectionConfig(anonymousLoginEnabled
                ,loginFailureDelay
                ,maxLogins
                ,maxAnonymousLogins
                ,maxLoginFailures
                ,maxThreads
        );
        serverFactory.setConnectionConfig(defaultConnectionConfig);
        //用户名
        BaseUser user = new BaseUser();
        user.setName(securityFtpUsername);
        //密码 如果不设置密码就是匿名用户
        user.setPassword(securityFtpPassword);
        //用户主目录
        user.setHomeDirectory(securityFtpRootDir);
        user.setEnabled(true);
        user.setMaxIdleTime(0);

        List<Authority> authorities = new ArrayList<Authority>();
        //增加写权限
        WritePermission writePermission = new WritePermission();
        authorities.add(writePermission);
        //速率限制
        TransferRatePermission transferRatePermission = new TransferRatePermission(0,0);
        authorities.add(transferRatePermission);
        //登录权限
        ConcurrentLoginPermission concurrentLoginPermission = new ConcurrentLoginPermission(10,10);
        authorities.add(concurrentLoginPermission);
        //设置权限集合
        user.setAuthorities(authorities);

        //增加该用户
        serverFactory.getUserManager().save(user);

        server = serverFactory.createServer();

        server.start();
        log.debug("FTP 服务启动成功，FTP监听端口:" + factory.getPort());
        return true;
    }


    @Override
    public Map<String, String> getSysconfigValByKeys(String... keys) {
        Map<String, String> map = new HashMap<>(16);
        if (ArrayUtils.isEmpty(keys)) {
            return map;
        }
        List<SysConfig> list = this.sysConfigMapper.getSysconfigValByKeys(keys);
        if (list != null && !list.isEmpty()) {
            for (SysConfig c : list) {
                String key = c.getConfigKey();
                if (!map.containsKey(key)) {
                    map.put(key, c.getConfigVal());
                }
            }
        }
        return map;
    }

    @Override
    public String getDefaultFtpDir() {
        String dir = SystemUtils.USER_DIR;
        return dir;
    }


}
